package org.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.Md5Crypt;
import org.apache.commons.lang3.StringUtils;
import org.example.enums.BizCodeEnum;
import org.example.enums.SendCodeEnum;
import org.example.feign.CouponFeignService;
import org.example.interceptor.LoginInterceptor;
import org.example.mapper.UserMapper;
import org.example.model.LoginUser;
import org.example.model.UserDO;
import org.example.request.NewUserCouponRequest;
import org.example.request.UserLoginRequest;
import org.example.request.UserRegisterRequest;
import org.example.service.NotifyService;
import org.example.service.UserService;
import org.example.util.CommonUtil;
import org.example.util.JsonData;
import org.example.util.JwtUtil;
import org.example.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private NotifyService notifyService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CouponFeignService couponFeignService;

    /**
     * 用户注册
     */
//    @GlobalTransactional
    @Override
    public JsonData register(UserRegisterRequest userRegisterRequest) {
        //1、检查验证码输入是否正确
        String code = userRegisterRequest.getCode();
        boolean checkCode = false;
        //1.1、邮箱是否存在
        if (StringUtils.isNotBlank(userRegisterRequest.getMail())) {
            checkCode = notifyService.checkCode(SendCodeEnum.USER_REGISTER,
                    userRegisterRequest.getMail(),
                    userRegisterRequest.getCode());
        }
        //1.2、验证码错误则返回
        if (!checkCode) {
            return JsonData.buildResult(BizCodeEnum.CODE_ERROR);
        }

        //2、检查账号是否重复
        boolean unique = checkUnique(userRegisterRequest.getMail());
        if (!unique) {
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_REPEAT);
        }

        //3、给UserDO赋值
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(userRegisterRequest, userDO);
        userDO.setCreateTime(new Date());

        //4、设置密码
        //4.1、生成随即盐
        userDO.setSecret("$1$" + CommonUtil.getStringNumRandom(8));
        //4.2、根据盐和密码进行加密
        String cryptPwd = Md5Crypt.md5Crypt(userRegisterRequest.getPwd().getBytes(), userDO.getSecret());
        userDO.setPwd(cryptPwd);

        //5、数据库中插入数据
        int rows = userMapper.insert(userDO);
        if (rows == 1) {
            log.info("影响行数: {}", rows);
            //6、发放福利和初始化信息
            userRegisterInit(userDO);
//            int i = 1 / 0;
            return JsonData.buildSuccess();
        }

        return JsonData.buildError("注册失败");
    }

    /**
     * 用户登录
     */
    @Override
    public JsonData userLogin(UserLoginRequest loginRequest) {
        //1、查询是否存在该用户
        QueryWrapper queryWrapper = new QueryWrapper<UserDO>().eq("mail", loginRequest.getMail());
        List<UserDO> userDOList = userMapper.selectList(queryWrapper);
        if (userDOList != null && userDOList.size() == 1) {
            UserDO userDO = userDOList.get(0);
            //2、比对密码
            String cryptPwd = Md5Crypt.md5Crypt(loginRequest.getPwd().getBytes(), userDO.getSecret());
            if (cryptPwd != null && cryptPwd.equals(userDO.getPwd())) {
                //登录成功生成token
                LoginUser loginUser = LoginUser.builder().build();
                BeanUtils.copyProperties(userDO, loginUser);
                String token = JwtUtil.geneJwtToken(loginUser);
                return JsonData.buildSuccess(token);
            }
            return JsonData.buildResult(BizCodeEnum.ACCOUNT_PWD_ERROR);
        }

        return JsonData.buildResult(BizCodeEnum.ACCOUNT_UNREGISTER);
    }

    /**
     * 查询用户个人信息
     */
    @Override
    public UserVO findUserDetail() {
        //1、获取用户ID
        Long userId = LoginInterceptor.threadLocal.get().getId();
        //2、查询用户信息
        UserDO userDO = userMapper.selectOne(new QueryWrapper<UserDO>().eq("id", userId));
        UserVO userVO = new UserVO();
        //3、复制属性
        BeanUtils.copyProperties(userDO, userVO);
        return userVO;
    }

    /**
     * 初始化用户信息
     */
    private void userRegisterInit(UserDO userDO) {
        NewUserCouponRequest request = new NewUserCouponRequest();
        request.setName(userDO.getName());
        request.setUserId(userDO.getId());
        JsonData jsonData = couponFeignService.addNewUserCoupon(request);
        if (jsonData.getCode() != 0) {
            throw new RuntimeException("发放优惠券失败");
        }
        log.info("新人发放优惠券:{}", jsonData);
    }

    /**
     * 检查账户唯一性
     */
    private boolean checkUnique(String mail) {
        QueryWrapper queryWrapper = new QueryWrapper<UserDO>().eq("mail", mail);
        List<UserDO> list = userMapper.selectList(queryWrapper);
        return list.size() > 0 ? false : true;
    }


}
